////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.more;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
//import android.graphics.Color;
//import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.ActivityGroup_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.stock.BMPCurrentStockInfoActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.CurrentStockInfoActivity;
import cc.telecomdigital.tdstock.adapter.ThreeTextColumnHolder;
import cc.telecomdigital.tdstock.adapter.ThreeTextColumnItemTwoAdapter;

/**
 * 
 * @author haibo
 * 
 *  for list item  named  "Instant Market"
 *
 */
public class InstantMarketContextActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String		TAG					= InstantMarketContextActivity.class.getSimpleName();
	
	private final static String			SEPARATORS			= "###";
	
	private String[]					_performance_res	= null;
	private String						_currency_res		= null;
	private String[]					_stockCodes;
	private SharedPreferences			_prefsStockCode;

	private ListView					_listView;
	private Button						_toolBtnReturn;
	private TextView					_contextTitle;

	private ThreeTextColumnItemTwoAdapter	_adapter;
	private List<ThreeTextColumnHolder>	_list;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.instant_market_context);

		_contextTitle = (TextView) findViewById(R.id.instant_market_context_title);
		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_listView = (ListView) findViewById(R.id.instant_market_context);

		_list = new ArrayList<ThreeTextColumnHolder>();

		_adapter = new ThreeTextColumnItemTwoAdapter(LayoutInflater.from(this), _list);

		_listView.setAdapter(_adapter);

		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_performance_res = new String[] {
				getResources().getString(R.string.performance_mo),
				getResources().getString(R.string.performance_zhong),
				getResources().getString(R.string.performance_ji),
				getResources().getString(R.string.performance_te) };
		_currency_res = getResources().getString(
				R.string.more_instant_market_currency);
		_progressTitle_res = getResources().getString(
				R.string.loading_indicator);
		_progressContent_res = getResources().getString(
				R.string.loading_mesgr);

		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(), InstantMarketActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				
				SwitchForwardActivity(InstantMarketActivity.class, intent);
			}
		});

		_listView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				if (_stockCodes == null
						|| _stockCodes.length < position + 1
						|| !TextUtils.isDigitsOnly(_stockCodes[position]
								.trim()))
				{
					return;
				}

				if (position != -1 && _stockCodes != null
						&& _stockCodes.length >= position + 1)
				{
					String stockCode = String.valueOf(Integer
							.parseInt(_stockCodes[position].trim()));
					_prefsStockCode = getSharedPreferences(
							CommonDefn.SYSTEM_CURRENT_SETTING,
							Context.MODE_PRIVATE);
					_prefsStockCode.edit().putString(
							CommonDefn.PREFERENCE_STOCK_CODE, stockCode)
							.commit();

					// BMP Mode  by ouyangzhihui 2011-10-13
					Class<? extends ActivityGroup_Framework>_cls = CurrentStockInfoActivity.class;
					if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
					{
						_cls = BMPCurrentStockInfoActivity.class;
					}
					
					Intent intent = new Intent(getApplicationContext(), _cls);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

					SwitchTabHostActivity(0, StockGroup.GetActivityGroupHostControl(), _cls,intent);
				}
			}
		});
	}

	private String[] cast(List<String[]> content, int pos)
	{
		String[] result = new String[content.size()];
		_stockCodes = new String[content.size()];
		int count = 0;
		for (String[] array : content)
		{
			_stockCodes[count] = array[(pos == 3 || pos == 5 || pos == 6) ? 0 : 1];
			count++;
		}

		switch (pos)
		{
			case 0:
			case 2:
				for (int index = 0, size = content.size(); index < size; index++)
				{
					String[] array = content.get(index);
					if (array != null && array.length >= 1)
					{
						StringBuffer tmp = new StringBuffer();
						String tmpStr = array[0].substring(
								array[0].length() > 10 ? 10 : 0).trim();
						tmp.append(tmpStr.substring(0,
								tmpStr.length() >= 5 ? 5 : tmpStr
										.length()));
						for (int item = 1, itemSize = array.length; item < itemSize; item++)
						{
							if (item == 1)
							{
								tmp
										.append(SEPARATORS)
										.append(
												String
														.format(
																"%05d",
																Integer
																		.parseInt(array[item])));
							}
							else
							{
								tmp.append(SEPARATORS).append(
										(array[item] == null ? ""
												: array[item]));
							}
						}
						result[index] = tmp.toString();
					}

				}
				break;
			case 1:
				for (int index = 0, size = content.size(); index < size; index++)
				{
					String[] array = content.get(index);
					if (array != null && array.length >= 1)
					{
						StringBuffer tmp = new StringBuffer(
								array[0]
										.substring(0, array[0]
												.length() > 10 ? 10
												: array[0].length()));
						for (int item = 1, itemSize = array.length; item < itemSize; item++)
						{
							if (item == 1)
							{
								tmp
										.append(SEPARATORS)
										.append(
												String
														.format(
																"%05d",
																Integer
																		.parseInt(array[item])));
							}
							else
							{
								tmp.append(SEPARATORS).append(
										(array[item] == null ? ""
												: array[item]));
							}
						}
						result[index] = tmp.toString();
					}
				}
				break;
			case 3:
				for (int index = 0, size = content.size(); index < size; index++)
				{
					String[] array = content.get(index);
					if (array != null && array.length >= 1)
					{
						StringBuffer tmp = new StringBuffer(String
								.format("%05d", Integer
										.parseInt(array[0])));
						for (int item = 1, itemSize = array.length; item < itemSize; item++)
						{
							try
							{
								if ((item == 3)
										&& (array[item].length() >= 10))
								{
									String tmpStr = array[item].trim()
											.substring(5, 10);
									array[item] = tmpStr.substring(3,
											5)
											+ "/"
											+ tmpStr.substring(0, 2); // MM-dd to dd/MM
								}
								if ((item == 2)
										&& (Integer.parseInt(
												array[item], 10) - 1 < _performance_res.length)
										&& Integer.parseInt(
												array[item], 10) - 1 >= 0)
								{
									array[item] = _performance_res[Integer
											.parseInt(array[item],
													10) - 1];
								}
								else if (item == 2)
								{
									array[item] = "";
								}
							}
							catch (NumberFormatException e)
							{
								e.printStackTrace();
							}
						}
						for (int item = 1, itemSize = array.length; item < itemSize; item++)
						{
							String str = (array[item] == null ? ""
									: array[item]);
							if (item == 2)
							{
								str = array[3];
							}
							if (item == 3)
							{
								str = array[2];
							}
							if (item <= 2)
							{
								tmp.append(SEPARATORS).append(str);
							}
							else
							{
								tmp.append(str);
							}

						}
						result[index] = tmp.toString();
					}
				}

				break;
			case 5:
				for (int index = 0, size = content.size(); index < size; index++)
				{
					String[] array = content.get(index);
					if (array != null && array.length >= 1)
					{
						StringBuffer tmp = new StringBuffer(String
								.format("%05d", Integer
										.parseInt(array[0])));
						for (int item = 1, itemSize = array.length; item < itemSize; item++)
						{
							try
							{
								if ((item == itemSize - 2)
										&& (array[item].length() >= 10))
								{
									String tmpStr = array[item].trim()
											.substring(5, 10);
									array[item] = tmpStr.substring(3,
											5)
											+ "/"
											+ tmpStr.substring(0, 2); // MM-dd to dd/MM
								}
								if ((item == itemSize - 1)
										&& (Integer.parseInt(
												array[item], 10) - 1 < _performance_res.length))
								{
									array[item] = _performance_res[Integer
											.parseInt(array[item],
													10) - 1];
								}
							}
							catch (NumberFormatException e)
							{
								array[item] = "";
								e.printStackTrace();
							}
							tmp.append(SEPARATORS).append(
									(array[item] == null ? ""
											: array[item]));
						}
						result[index] = tmp.toString();
					}
				}
				break;
			case 4:
				for (int index = 0, size = content.size(); index < size; index++)
				{
					String[] array = content.get(index);
					if (array != null && array.length >= 1)
					{
						StringBuffer tmp = new StringBuffer(array[0]
								.substring(0, 10));
						tmp.append(SEPARATORS).append(
								String.format("%05d", Integer
										.parseInt(array[1])));
						for (int item = 2, itemSize = array.length; item < itemSize; item++)
						{
							tmp.append(SEPARATORS).append(
									(array[item] == null ? ""
											: array[item]));
						}
						result[index] = tmp.toString();
					}

				}
				break;
			case 6:
				for (int index = 0, size = content.size(); index < size; index++)
				{
					String[] array = content.get(index);
					if (array != null && array.length >= 1)
					{
						StringBuffer tmp = new StringBuffer(String
								.format("%05d", Integer
										.parseInt(array[0])));
						tmp.append(SEPARATORS).append(_currency_res);
						for (int item = 1, itemSize = array.length; item < itemSize; item++)
						{
							tmp.append(SEPARATORS).append(
									array[item] == null ? ""
											: array[item]);
						}
						result[index] = tmp.toString();
					}
				}
				break;
			default:

		}
		return result;
	}

	private int iTypeId = 0;
	
	@Override
	protected void onResume()
	{
		SetExectuHttpRequestOnResume(false);
		
		super.onResume();
		
		ITDLApplication app = (ITDLApplication) getApplicationContext();
		if (app.getId() == 0 || app.getId() == 1 || app.getId() == 2 || app.getId() == 4 || app.getId() == 6)
		{
			_listView.setDividerHeight(0);
		}
		else
		{
			_listView.setDividerHeight(1);
		}
		
		if (app.getDataMode() == CommonDefn.DataMode.Delay)
		{
			if (app.getId() == 0 || app.getId() == 2)
			{
				_contextTitle.setText(app.getState());
				_contextTitle.postInvalidate();
				
				resetContent();
				
				{
					ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
					holder.left = new TextView(this);
					holder.right = new TextView(this);
					holder.mid = new TextView(this);
					holder.id = 90000;
					holder.left.setText("");
					holder.mid.setText(getResources().getString(R.string.delay_mode_chargeable_data_tips));
					holder.right.setText("");
					_list.add(holder);
				}

				_adapter.notifyDataSetChanged();
				_listView.postInvalidate();
				return;
			}
		}
		
		SendHttpRequest();
		_listView.invalidateViews();		
	}
	
	private void resetContent()
	{
		_list.clear();
		_adapter.notifyDataSetChanged();
	}
	
	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}
	
	private  void setNoDataTips(){
		if(_list.isEmpty())
		{
			ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
			holder.left = new TextView(this);
			holder.right = new TextView(this);
			holder.mid = new TextView(this);
			holder.id = 90001;
			holder.left.setText("");
			holder.mid.setText("");
			holder.right.setText(getResources().getString(R.string.provide_no_information));
			_list.add(holder);
		}
	}
	
	private void updateData(String[] items)
	{
		if (items != null && items.length >= 1)
		{
			_list.clear();
			int start_id = 90000;
			for (String item : items)
			{
				TDStockLog.d(TAG, "ITEM: "+item);
				String[] element = item.split(SEPARATORS);
				if (element.length == 3 || element.length == 4)
				{
					ThreeTextColumnHolder holder = new ThreeTextColumnHolder();
					holder.left = new TextView(InstantMarketContextActivity.this);
					holder.right = new TextView(InstantMarketContextActivity.this);
					holder.mid = new TextView(InstantMarketContextActivity.this);
					holder.id = start_id++;
					holder.left.setText(element[0]);
					holder.mid.setText(element[1]);
					holder.right.setText(element.length == 3 ? element[2] : (element[2] + element[3]));
					_list.add(holder);
				}
			}
			setNoDataTips();
			_adapter.notifyDataSetChanged();
			_listView.postInvalidate();
		}
		else
		{
			if (_adapter != null)
			{
				_list.clear();
				setNoDataTips();
				_adapter.notifyDataSetChanged();
				_listView.postInvalidate();
			}
		}
	}

	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		ITDLApplication app = (ITDLApplication) getApplicationContext();
		
		_contextTitle.setText(app.getState());
		resetContent();
		
		iTypeId = app.getId();
		
		return HttpAppInfo.SendInstantMarketRequest(actContext, iTypeId, this);
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if(!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError+"("+iResult.MStatus+")");
			return;
		}
		
		Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				String[] items = cast(iResult.contentStores, iTypeId);
				updateData(items);
			}
		};
		_messageHandler.post(runnable);
	}
}
